package com.jie.eduservice.controller;


import com.jie.commonutils.ResultEntity;
import com.jie.eduservice.client.VodClient;
import com.jie.eduservice.entity.EduVideo;
import com.jie.eduservice.service.EduVideoService;
import com.jie.servicebase.exception.GuLiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author xzj
 * @since 2020-10-09
 */
//@CrossOrigin  // 解决跨域问题
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {

    private final EduVideoService videoService;

    // 用于调用service-vod服务的接口
    private final VodClient vodClient;

    @Autowired
    public EduVideoController(
            EduVideoService videoService,
            VodClient vodClient
    ) {
        this.videoService = videoService;
        this.vodClient = vodClient;
    }

    // 添加小节
    @PostMapping("/addVideo")
    public ResultEntity addVideo(
            @RequestBody EduVideo eduVideo
            ) {
        videoService.save(eduVideo);
        return ResultEntity.ok();
    }

    // 删除小节
    @DeleteMapping("/{id}")
    public ResultEntity deleteVideo(
            @PathVariable("id") String id
    ) {
        EduVideo eduVideo = videoService.getById(id);
        if (!StringUtils.isEmpty(eduVideo.getVideoSourceId())) {
            // 根据小节id获取视频id, 然后执行删除
            ResultEntity resultEntity = vodClient.removeAliVideo(eduVideo.getVideoSourceId());
            if (resultEntity.getCode() == 20001) {
                System.out.println(resultEntity.getMessage() + " 触发了熔断器! ");
                throw new GuLiException(20001, resultEntity.getMessage() + " 触发了熔断器! ");
            }
        }
        videoService.removeById(id);
        return ResultEntity.ok();
    }

    // 根据小节id查询小节
    @GetMapping("/getVideoInfo/{videoId}")
    public ResultEntity getVideoInfo(
            @PathVariable("videoId") String videoId
    ) {
        EduVideo eduVideo = videoService.getById(videoId);
        return ResultEntity.ok().data("video", eduVideo);
    }

    // 修改小节
    @PostMapping("/updateVideo")
    public ResultEntity updateVideo(
            @RequestBody EduVideo eduVideo
    ) {
        videoService.updateById(eduVideo);
        return ResultEntity.ok();
    }

}

